/**
 * 文件处理工具函数
 */

import * as XLSX from 'xlsx';
import JSZip from 'jszip';
import { UploadFile, LanguageFile } from '../types';

/**
 * 验证文件类型
 */
export const validateFileType = (file: File): boolean => {
  const allowedTypes = [
    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    'application/vnd.ms-excel',
  ];
  return allowedTypes.includes(file.type);
};

/**
 * 验证文件大小
 */
export const validateFileSize = (file: File, maxSizeMB: number = 10): boolean => {
  const maxSizeBytes = maxSizeMB * 1024 * 1024;
  return file.size <= maxSizeBytes;
};

/**
 * 创建上传文件对象
 */
export const createUploadFile = (file: File): UploadFile => {
  return {
    file,
    name: file.name,
    size: file.size,
    type: file.type,
  };
};

/**
 * 解析Excel文件
 */
export const parseExcelFile = async (file: File): Promise<LanguageFile[]> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    
    reader.onload = (e) => {
      try {
        const data = e.target?.result;
        if (!data) {
          reject(new Error('文件读取失败'));
          return;
        }

        const workbook = XLSX.read(data, { type: 'binary' });
        const sheetName = workbook.SheetNames[0];
        const worksheet = workbook.Sheets[sheetName];
        
        // 转换为JSON格式
        const jsonData = XLSX.utils.sheet_to_json(worksheet, { header: 1 });
        
        if (jsonData.length < 2) {
          reject(new Error('Excel文件格式不正确，至少需要2行数据'));
          return;
        }

        // 第一行是语言代码
        const languageCodes = jsonData[0] as string[];
        const languageFiles: LanguageFile[] = [];

        // 从第二行开始是翻译数据
        for (let i = 1; i < jsonData.length; i++) {
          const row = jsonData[i] as string[];
          if (!row[0]) continue; // 跳过空的键

          const key = row[0].trim();
          if (!key) continue;

          // 为每个语言创建数据
          for (let j = 1; j < languageCodes.length; j++) {
            const languageCode = languageCodes[j]?.trim();
            if (!languageCode) continue;

            // 生成完整的语言代码格式 (languageCode_countryCode)
            const fullLanguageCode = generateFullLanguageCode(languageCode);
            
            // 查找或创建语言文件
            let languageFile = languageFiles.find(f => f.code === fullLanguageCode);
            if (!languageFile) {
              languageFile = {
                language: getLanguageName(languageCode),
                code: fullLanguageCode,
                data: {},
                fileName: `${fullLanguageCode}.dart`,
              };
              languageFiles.push(languageFile);
            }

            // 添加翻译数据
            const translation = row[j]?.trim() || '';
            languageFile.data[key] = translation;
          }
        }

        resolve(languageFiles);
      } catch (error) {
        reject(new Error(`Excel文件解析失败: ${error instanceof Error ? error.message : '未知错误'}`));
      }
    };

    reader.onerror = () => {
      reject(new Error('文件读取失败'));
    };

    reader.readAsBinaryString(file);
  });
};

/**
 * 生成完整的语言代码格式 (languageCode_countryCode)
 */
const generateFullLanguageCode = (code: string): string => {
  // 如果已经是完整格式，直接返回
  if (code.includes('_')) {
    return code;
  }
  
  // 语言代码到完整代码的映射
  const languageCodeMap: { [key: string]: string } = {
    'en': 'en_US',
    'zh': 'zh_CN',
    'zh_CN': 'zh_CN',
    'zh_HK': 'zh_HK',
    'cn': 'zh_CN',        // 特殊处理：cn -> zh_CN
    'hk': 'zh_HK',        // 特殊处理：hk -> zh_HK
    'ar': 'ar_AR',
    'cs': 'cs_CS',
    'da': 'da_DA',
    'de': 'de_DE',
    'el': 'el_EL',
    'es': 'es_ES',
    'fa': 'fa_FA',
    'fi': 'fi_FI',
    'fr': 'fr_FR',
    'ga': 'ga_GA',
    'he': 'he_HE',
    'hr': 'hr_HR',
    'hu': 'hu_HU',
    'it': 'it_IT',
    'ja': 'ja_JA',
    'ko': 'ko_KO',
    'nb': 'nb_NB',
    'pl': 'pl_PL',
    'pt': 'pt_PT',
    'ro': 'ro_RO',
    'ru': 'ru_RU',
    'sk': 'sk_SK',
    'sv': 'sv_SV',
    'th': 'th_TH',
    'tr': 'tr_TR',
    'uk': 'uk_UK',
    'vi': 'vi_VI',
  };
  
  return languageCodeMap[code] || `${code}_${code.toUpperCase()}`;
};

/**
 * 获取语言名称
 */
const getLanguageName = (code: string): string => {
  const languageMap: { [key: string]: string } = {
    'en': 'English',
    'zh': '中文',
    'zh_CN': '简体中文',
    'zh_HK': '繁体中文(香港)',
    'cn': '简体中文',        // 特殊处理：cn -> 简体中文
    'hk': '繁体中文(香港)',   // 特殊处理：hk -> 繁体中文(香港)
    'ar': 'العربية',
    'cs': 'Čeština',
    'da': 'Dansk',
    'de': 'Deutsch',
    'el': 'Ελληνικά',
    'es': 'Español',
    'fa': 'فارسی',
    'fi': 'Suomi',
    'fr': 'Français',
    'ga': 'Gaeilge',
    'he': 'עברית',
    'hr': 'Hrvatski',
    'hu': 'Magyar',
    'it': 'Italiano',
    'ja': '日本語',
    'ko': '한국어',
    'nb': 'Norsk',
    'pl': 'Polski',
    'pt': 'Português',
    'ro': 'Română',
    'ru': 'Русский',
    'sk': 'Slovenčina',
    'sv': 'Svenska',
    'th': 'ไทย',
    'tr': 'Türkçe',
    'uk': 'Українська',
    'vi': 'Tiếng Việt',
  };
  
  return languageMap[code] || code;
};

/**
 * 格式化文件大小
 */
export const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024;
  const sizes = ['Bytes', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
};

/**
 * 生成文件下载链接
 */
export const createDownloadLink = (content: string): string => {
  const blob = new Blob([content], { type: 'text/plain;charset=utf-8' });
  const url = URL.createObjectURL(blob);
  return url;
};

/**
 * 下载文件
 */
export const downloadFile = (content: string, fileName: string): void => {
  const link = document.createElement('a');
  link.href = createDownloadLink(content);
  link.download = fileName;
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(link.href);
};

/**
 * 生成ZIP文件并下载
 */
export const downloadAllFilesAsZip = async (files: LanguageFile[], dartContentGenerator: (file: LanguageFile) => string): Promise<void> => {
  const zip = new JSZip();
  
  // 添加所有语言文件到ZIP
  files.forEach(file => {
    const dartContent = dartContentGenerator(file);
    zip.file(file.fileName, dartContent);
  });
  
  // 生成ZIP文件
  const zipBlob = await zip.generateAsync({ type: 'blob' });
  
  // 创建下载链接
  const url = URL.createObjectURL(zipBlob);
  const link = document.createElement('a');
  link.href = url;
  link.download = 'language_files.zip';
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
  URL.revokeObjectURL(url);
};
